import {Physics, Scene} from "phaser";
import {BottomHeight} from "@/sys/resource.ts";

export class Player extends Physics.Arcade.Sprite {
    private isDown: boolean = false;
    private downX: number = 0;
    private downY: number = 0;
    private bottom: number = 40;

    constructor(scene: Scene) {
        let {width, height} = scene.cameras.main;
        super(scene, width / 2, height - BottomHeight - 40, 'SpritePlane');
        scene.add.existing(this);
        scene.physics?.add.existing(this);

        this.setInteractive();
        this.setCollideWorldBounds(true);

        this.anims.create({
            key: 'PlaneAnim',
            frames: this.anims.generateFrameNumbers('SpritePlane', {start: 0, end: 5}),
            repeat: -1,
        });
        this.play('PlaneAnim');
        this.addEvent();
    }

    addEvent() {
        const height = this.scene.cameras.main.height;
        this.on("pointerdown", () => {
            this.isDown = true;
            this.downX = this.x;
            this.downY = this.y;
        });
        this.scene.input.on("pointerup", () => {
            this.isDown = false;
        });
        this.scene.input.on("pointermove", (pointer: any) => {
            if (this.isDown) {
                if (pointer.x >= this.bottom && pointer.x <= this.scene.cameras.main.width - this.bottom) {
                    this.x = this.downX + pointer.x - pointer.downX;
                }
                const y = this.downY + pointer.y - pointer.downY;
                if (y < height - BottomHeight) {
                    this.y = y;
                }
            }
        });
    }
}